import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, InputNumber } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import PackageForm from './PackageForm';
import PackageDetail from './PackageDetail';

const { Option } = Select;

// 获取场地预约套餐列表
const fetchPackages = async (params) => {
    return request('/api/v1/venue/package', {
        method: 'GET',
        params,
    });
};



// 创建场地预约套餐
const createPackage = async (data) => {
    return request('/api/v1/venue/package', {
        method: 'POST',
        data,
    });
};

// 更新场地预约套餐
const updatePackage = async (id, data) => {
    return request(`/api/v1/venue/package/${id}`, {
        method: 'PUT',
        data,
    });
};

// 删除场地预约套餐
const deletePackage = async (id) => {
    return request(`/api/v1/venue/package/${id}`, {
        method: 'DELETE',
    });
};

// 获取门店列表
const fetchStores = async () => {
    return request('/api/v1/store', {
        method: 'GET',
        params: { pageSize: 100 },
    });
};

// 获取场地列表
const fetchVenues = async (storeId) => {
    const params = { pageSize: 100 };
    if (storeId) {
        params.store_id = storeId;
    }
    return request('/api/v1/venue', {
        method: 'GET',
        params,
    });
};

const VenuePackage = () => {
    const [packages, setPackages] = useState([]);
    const [stores, setStores] = useState([]);
    const [venues, setVenues] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [packageForm] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [searchParams, setSearchParams] = useState({});
    const [detailVisible, setDetailVisible] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [currentPackage, setCurrentPackage] = useState(null);
    const [formTitle, setFormTitle] = useState('创建场地预约套餐');
    const [selectedStores, setSelectedStores] = useState([]);
    const [selectedVenues, setSelectedVenues] = useState([]);
    const [storeTargetKeys, setStoreTargetKeys] = useState([]);
    const [venueTargetKeys, setVenueTargetKeys] = useState([]);
    const [formKey, setFormKey] = useState(0);

    // 获取场地预约套餐列表
    const fetchPackageList = async () => {
        try {
            setLoading(true);
            const res = await fetchPackages({
                page: pagination.current,
                pageSize: pagination.pageSize,
                ...searchParams,
            });
            if (res.success) {
                setPackages(res.data.list || []);
                setPagination({
                    ...pagination,
                    total: res.data.total,
                });
            } else {
                message.error(res.message || '获取场地预约套餐列表失败');
            }
        } catch (error) {
            console.error('获取场地预约套餐列表出错:', error);
            message.error('获取场地预约套餐列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取门店列表
    const fetchStoreList = async () => {
        try {
            const res = await fetchStores();
            if (res.success) {
                const storeList = res.data.list || [];
                setStores(storeList);
                // 转换为Transfer需要的数据格式
                setSelectedStores(storeList.map(store => ({
                    key: store.id.toString(),
                    title: store.name,
                    description: store.address,
                })));
            } else {
                message.error(res.message || '获取门店列表失败');
            }
        } catch (error) {
            console.error('获取门店列表出错:', error);
            message.error('获取门店列表失败');
        }
    };

    // 获取场地列表
    const fetchVenueList = async () => {
        try {
            const res = await fetchVenues();
            if (res.success) {
                const venueList = res.data.list || [];
                setVenues(venueList);
                // 转换为Transfer需要的数据格式
                setSelectedVenues(venueList.map(venue => ({
                    key: venue.id.toString(),
                    title: venue.name,
                    description: `${stores.find(s => s.id === venue.store_id)?.name || ''} - ${venue.venue_type}`,
                })));
            } else {
                message.error(res.message || '获取场地列表失败');
            }
        } catch (error) {
            console.error('获取场地列表出错:', error);
            message.error('获取场地列表失败');
        }
    };

    useEffect(() => {
        fetchPackageList();
        fetchStoreList();
    }, [pagination.current, pagination.pageSize, searchParams]);

    useEffect(() => {
        if (stores.length > 0) {
            fetchVenueList();
        }
    }, [stores]);

    // 查看场地预约套餐详情
    const handleViewDetail = (record) => {
        setCurrentPackage(record);
        setDetailVisible(true);
    };

    // 处理添加场地预约套餐
    const handleAdd = () => {
        setFormTitle('创建场地预约套餐');
        setCurrentPackage(null);
        packageForm.resetFields();
        setFormKey(prev => prev + 1); // 每次新建强制刷新表单
        // 确保available_times是一个数组
        packageForm.setFieldsValue({
            status: 1,
            duration: 1,
            sort_order: 0,
            available_weekdays: [1, 2, 3, 4, 5, 6, 7],
            available_times: [{ timeRange: [moment('00:00', 'HH:mm'), moment('23:59', 'HH:mm')] }],
        });
        setStoreTargetKeys([]);
        setVenueTargetKeys([]);
        setFormVisible(true);
    };
    
    // 处理编辑场地预约套餐
    const handleEdit = (record) => {
        setFormTitle('编辑场地预约套餐');
        let cPackage = {...record};
        packageForm.resetFields();
        setFormKey(prev => prev + 1); // 每次编辑强制刷新表单
        // 解析门店和场地ID
        let storeIds = [];
        let venueIds = [];
        let availableWeekdays = [];
        let availableTimes = [];
    
        try {
            if (record.stores) {
                storeIds = JSON.parse(record.stores).map(id => id.toString());
            }
        } catch (e) {
            console.error('解析门店ID出错:', e);
        }
    
        try {
            if (record.venues) {
                venueIds = JSON.parse(record.venues).map(id => id.toString());
            }
        } catch (e) {
            console.error('解析场地ID出错:', e);
        }
    
        try {
            if (record.available_weekdays) {
                availableWeekdays = JSON.parse(record.available_weekdays);
            }
        } catch (e) {
            console.error('解析可用星期出错:', e);
        }
    
        try {
            if (record.available_times) {
                const times = JSON.parse(record.available_times);
                if (Array.isArray(times) && times.length > 0) {
                    availableTimes = times.map(t => ({
                        timeRange: [moment(t.start, 'HH:mm'), moment(t.end, 'HH:mm')]
                    }));
                } else {
                    // 确保availableTimes是数组
                    availableTimes = [{ timeRange: [moment('00:00', 'HH:mm'), moment('23:59', 'HH:mm')] }];
                }
            } else {
                availableTimes = [{ timeRange: [moment('00:00', 'HH:mm'), moment('23:59', 'HH:mm')] }];
            }
        } catch (e) {
            console.error('解析可用时间段出错:', e);
            availableTimes = [{ timeRange: [moment('00:00', 'HH:mm'), moment('23:59', 'HH:mm')] }];
        }
        
        setStoreTargetKeys(storeIds);
        setVenueTargetKeys(venueIds);
    
        packageForm.setFieldsValue({
            name: record.name,
            description: record.description,
            price: record.price,
            duration: record.duration,
            status: record.status,
            sort_order: record.sort_order,
            available_weekdays: availableWeekdays,
            available_times: availableTimes,
        });
        setCurrentPackage({...cPackage, available_times: availableTimes, available_weekdays: availableWeekdays});
        setFormVisible(true);
    };

    // 处理删除场地预约套餐
    const handleDelete = async (id) => {
        try {
            setLoading(true);
            const res = await deletePackage(id);
            if (res.success) {
                message.success('删除场地预约套餐成功');
                fetchPackageList();
            } else {
                message.error(res.message || '删除场地预约套餐失败');
            }
        } catch (error) {
            console.error('删除场地预约套餐出错:', error);
            message.error('删除场地预约套餐失败');
        } finally {
            setLoading(false);
        }
    };

    // 提交表单
    const handleFormSubmit = async () => {
        try {
            const values = await packageForm.validateFields();
            setLoading(true);

            // 处理门店和场地ID
            values.stores = JSON.stringify(storeTargetKeys.map(id => parseInt(id)));
            values.venues = JSON.stringify(venueTargetKeys.map(id => parseInt(id)));

            // 处理可用时间
            if (values.available_times) {
                values.available_times = JSON.stringify(values.available_times.map(t => {
                    if (t && t.timeRange) {
                        return {
                            start: t.timeRange[0].format('HH:mm'),
                            end: t.timeRange[1].format('HH:mm'),
                        }
                    }
                    return null;
                }).filter(t => t !== null));
            }

            // 处理可用星期
            if (values.available_weekdays) {
                values.available_weekdays = JSON.stringify(values.available_weekdays);
            }

            let res;
            if (currentPackage) {
                // 更新
                res = await updatePackage(currentPackage.id, values);
            } else {
                // 创建
                res = await createPackage(values);
            }

            if (res.success) {
                message.success(`${currentPackage ? '更新' : '创建'}场地预约套餐成功`);
                setFormVisible(false);
                fetchPackageList();
            } else {
                message.error(res.message || `${currentPackage ? '更新' : '创建'}场地预约套餐失败`);
            }
        } catch (error) {
            console.error(`${currentPackage ? '更新' : '创建'}场地预约套餐出错:`, error);
            message.error(`${currentPackage ? '更新' : '创建'}场地预约套餐失败`);
        } finally {
            setLoading(false);
        }
    };

    // 处理搜索
    const handleSearch = (values) => {
        const params = {};
        if (values.name) {
            params.name = values.name;
        }
        if (values.status !== undefined) {
            params.status = values.status;
        }

        setSearchParams(params);
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理重置
    const handleReset = () => {
        form.resetFields();
        setSearchParams({});
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理门店选择变化
    const handleStoreChange = (nextTargetKeys) => {
        setStoreTargetKeys(nextTargetKeys);
    };

    // 处理场地选择变化
    const handleVenueChange = (nextTargetKeys) => {
        setVenueTargetKeys(nextTargetKeys);
    };

    // 表格列定义
    const columns = [
        {
            title: '套餐名称',
            dataIndex: 'name',
            key: 'name',
            width: 150,
        },
        {
            title: '套餐描述',
            dataIndex: 'description',
            key: 'description',
            width: 200,
        },
        {
            title: '套餐价格',
            dataIndex: 'price',
            key: 'price',
            width: 120,
            render: (text) => `¥${(text).toFixed(2)}`,
        },
        {
            title: '使用时长',
            dataIndex: 'duration',
            key: 'duration',
            width: 120,
            render: (text) => `${text}小时`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => {
                let color = 'default';
                let text = '未知';

                switch (status) {
                    case 1: // 启用
                        color = 'green';
                        text = '启用';
                        break;
                    case 0: // 禁用
                        color = 'red';
                        text = '禁用';
                        break;
                    default:
                        color = 'default';
                        text = '未知';
                }

                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            width: 180,
            render: (text) => moment(text * 1000).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除此套餐吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="link" danger icon={<DeleteOutlined />}>
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];
    
    // 处理表格分页、排序、筛选变化
    const handleTableChange = (pagination, filters, sorter) => {
        setPagination(pagination);
    };

    return (
        <PageContainer>
            <Card style={{ marginBottom: 24 }}>
                <Form
                    form={form}
                    layout="inline"
                    onFinish={handleSearch}
                    style={{ marginBottom: 24 }}
                >
                    <Form.Item name="name" label="套餐名称">
                        <Input placeholder="请输入套餐名称" style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name="status" label="状态">
                        <Select placeholder="请选择状态" style={{ width: 200 }} allowClear>
                            <Option value={1}>启用</Option>
                            <Option value={0}>禁用</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={handleReset}>重置</Button>
                        </Space>
                    </Form.Item>
                </Form>

                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                        创建场地预约套餐
                    </Button>
                </div>

                <Table
                    columns={columns}
                    dataSource={packages}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    onChange={handleTableChange}
                    scroll={{ x: 1200 }}
                />
            </Card>

            <PackageDetail
                visible={detailVisible}
                onCancel={() => setDetailVisible(false)}
                packageId={currentPackage?.id}
                stores={stores}
                venues={venues}
            />

            <PackageForm
                visible={formVisible}
                formTitle={formTitle}
                onCancel={() => setFormVisible(false)}
                formKey={formKey}
                packageForm={packageForm}
                handleFormSubmit={handleFormSubmit}
                currentPackage={currentPackage}
                loading={loading}
                selectedStores={selectedStores}
                storeTargetKeys={storeTargetKeys}
                handleStoreChange={handleStoreChange}
                selectedVenues={selectedVenues}
                venueTargetKeys={venueTargetKeys}
                handleVenueChange={handleVenueChange}
            />
        </PageContainer>
    );
};

export default VenuePackage;
